<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PDF添加水印</title>
  <script src="../js/pdf-lib.min.js"></script>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #ffffff;
      color: #333;
      margin: 0;
      padding: 20px;
    }

    .input-row {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-bottom: 20px;
      justify-content: center;
      align-items: center;
    }

    .input-row input[type="file"] {
      position: relative;
      overflow: hidden;
      display: inline-block;
      padding: 10px 20px;
      border: 1px solid #ccc;
      border-radius: 5px;
      background-color: #f9f9f9;
      cursor: pointer;
    }

    .input-row input[type="file"]::before {
      display: inline-block;
      background: linear-gradient(top, #f9f9f9, #e3e3e3);
      border: 1px solid #999;
      border-radius: 3px;
      padding: 5px 8px;
      outline: none;
      white-space: nowrap;
      -webkit-user-select: none;
      cursor: pointer;
      text-shadow: 1px 1px #fff;
      font-weight: 700;
      font-size: 10pt;
    }

    .input-row input[type="file"] input[type="file"] {
      position: absolute;
      top: 0;
      right: 0;
      margin: 0;
      padding: 0;
      font-size: 20px;
      cursor: pointer;
      opacity: 0;
      filter: alpha(opacity=0);
    }

    .input-row input,
    .input-row button {
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 16px;
    }

    .input-row input[type="color"] {
      -webkit-appearance: none;
      padding: 0;
      border: none;
      width: 40px;
      height: 40px;
      cursor: pointer;
      border-radius: 50%;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
    }

    .input-row input[type="color"]::-webkit-color-swatch-wrapper {
      padding: 0;
    }

    .input-row input[type="color"]::-webkit-color-swatch {
      border: none;
      border-radius: 50%;
    }

    .add-watermark-button {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .add-watermark-button:hover {
      background: linear-gradient(135deg, #566bc7 0%, #633e88 100%);
    }

    .cancel-button {
      background-color: #808080;
      color: white;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .cancel-button:hover {
      background-color: #696969;
    }

    .preview-row {
      display: flex;
      gap: 20px;
    }

    .preview-row div {
      flex: 1;
      border: 1px solid #ccc;
      border-radius: 5px;
      padding: 10px;
      background-color: #f9f9f9;
    }

    .preview-row h2 {
      margin-top: 0;
      text-align: center;
    }

    .preview-row embed {
      width: 100%;
      height: 600px;
    }

    .modal {
      display: none;
      position: fixed;
      z-index: 1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0, 0, 0, 0.4);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 30%;
      border-radius: 8px;
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
      text-align: center;
    }

    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
    }

    .close:hover,
    .close:focus {
      color: black;
      text-decoration: none;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div class="input-row">
    <input type="file" id="pdfInput" accept=".pdf">
    <input type="text" id="watermarkText" placeholder="输入水印文本">
    <input type="color" id="watermarkColor" value="#808080">
    <input type="number" id="watermarkFontSize" placeholder="输入水印字体大小" value="30">
    <input type="number" id="watermarkRotation" placeholder="输入水印倾斜度（度）" value="-45">
    <input type="number" id="watermarkOpacity" placeholder="输入水印透明度（0 - 1）" value="0.5">
    <button class="add-watermark-button" onclick="addWatermark()">添加水印</button>
    <button class="cancel-button" onclick="cancelAction()">取消</button>
  </div>
  <div class="preview-row">
    <div>
      <h2>文件预览</h2>
      <embed id="originalPdfPreview" type="application/pdf">
    </div>
    <div>
      <h2>水印预览</h2>
      <embed id="watermarkedPdfPreview" type="application/pdf">
    </div>
  </div>

  <div id="myModal" class="modal">
    <div class="modal-content">
      <span class="close">&times;</span>
      <p id="modal-message"></p>
    </div>
  </div>

  <script>
    const pdfInput = document.getElementById('pdfInput');
    const watermarkText = document.getElementById('watermarkText');
    const watermarkColor = document.getElementById('watermarkColor');
    const watermarkFontSize = document.getElementById('watermarkFontSize');
    const watermarkRotation = document.getElementById('watermarkRotation');
    const watermarkOpacity = document.getElementById('watermarkOpacity');
    const originalPdfPreview = document.getElementById('originalPdfPreview');
    const watermarkedPdfPreview = document.getElementById('watermarkedPdfPreview');
    const modal = document.getElementById('myModal');
    const span = document.getElementsByClassName("close")[0];
    const modalMessage = document.getElementById('modal-message');

    watermarkText.addEventListener('input', function () {
      this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
    });

    pdfInput.addEventListener('change', function () {
      const file = this.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
          const arrayBuffer = e.target.result;
          originalPdfPreview.src = URL.createObjectURL(new Blob([arrayBuffer], { type: 'application/pdf' }));
        };
        reader.readAsArrayBuffer(file);
      }
    });

    async function addWatermark() {
      const file = pdfInput.files[0];
      if (!file) {
        showModal('请选择一个 PDF 文件');
        return;
      }
      const text = watermarkText.value;
      if (!text) {
        showModal('请输入水印文本');
        return;
      }
      const color = watermarkColor.value;
      const fontSize = parseInt(watermarkFontSize.value, 10);
      const rotation = parseFloat(watermarkRotation.value);
      const opacity = parseFloat(watermarkOpacity.value);

      const reader = new FileReader();
      reader.onload = async function (e) {
        const arrayBuffer = e.target.result;
        const pdfDoc = await PDFLib.PDFDocument.load(arrayBuffer);
        const pages = pdfDoc.getPages();

        const defaultFont = await pdfDoc.embedFont(PDFLib.StandardFonts.Helvetica);

        const textWidth = defaultFont.widthOfTextAtSize(text, fontSize);
        const textHeight = defaultFont.heightAtSize(fontSize);

        const [r, g, b] = hexToRgb(color);
        for (const page of pages) {
          const { width, height } = page.getSize();
          page.drawText(text, {
            x: (width - textWidth) / 2,
            y: (height - textHeight) / 2,
            size: fontSize,
            font: defaultFont,
            color: PDFLib.rgb(r / 255, g / 255, b / 255),
            rotate: PDFLib.degrees(rotation),
            opacity: opacity
          });
        }
        const pdfBytes = await pdfDoc.save();
        watermarkedPdfPreview.src = URL.createObjectURL(new Blob([pdfBytes], { type: 'application/pdf' }));
      };
      reader.readAsArrayBuffer(file);
    }

    function hexToRgb(hex) {
      const bigint = parseInt(hex.slice(1), 16);
      const r = (bigint >> 16) & 255;
      const g = (bigint >> 8) & 255;
      const b = bigint & 255;
      return [r, g, b];
    }

    function cancelAction() {
      pdfInput.value = '';
      watermarkText.value = '';
      watermarkColor.value = '#808080';
      watermarkFontSize.value = '30';
      watermarkRotation.value = '-45';
      watermarkOpacity.value = '0.5';
      originalPdfPreview.src = '';
      watermarkedPdfPreview.src = '';
    }

    function showModal(message) {
      modalMessage.textContent = message;
      modal.style.display = "block";
    }

    span.onclick = function () {
      modal.style.display = "none";
    }

    window.onclick = function (event) {
      if (event.target == modal) {
        modal.style.display = "none";
      }
    }
  </script>
</body>

</html>
    